package com.guoguo.sincemusic.logic.dao

import android.content.Context
import androidx.core.content.edit
import com.google.gson.Gson
import com.guoguo.sincemusic.MyApplication
import com.guoguo.sincemusic.logic.model.UserInfo

/**
 * @author GuoGuo
 * @date 2021/12/15
 */
object Storage {
    private fun sharePreferences() =
        MyApplication.context.getSharedPreferences("app_userInfo", Context.MODE_PRIVATE)

    //存储String类型信息
    fun setPreString(key: String, value: String) {
        sharePreferences().edit {
            putString(key, value)
        }
    }

    //存储Boolean类型信息
    fun setPreBoolean(key: String, value: Boolean) {
        sharePreferences().edit {
            putBoolean(key, value)
        }
    }

    //读取String 类型信息
    fun getPreString(key: String): String? {
        return sharePreferences().getString(key, " ")
    }

    //读取Boolean 类型信息
    fun getPreBoolean(key: String): Boolean {
        return sharePreferences().getBoolean(key, false)
    }

    //  判断用户是否登录
    fun isLogin(): Boolean {
        return getPreBoolean("isLogin")
    }

    /**
     * 存储用户信息
     * 获取编辑器 ，存储字段
     * @param userInfo
     */
    fun saveUserInfo(userInfo: UserInfo) {
        setPreString("userInfo", Gson().toJson(userInfo))
        setPreBoolean("isLogin", true)
    }

    /**
     * 获取用户信息
     * @return UserInfo
     */
    fun getUserInfo(): UserInfo {
        val userJson: String? = getPreString("userInfo")
        return Gson().fromJson(userJson, UserInfo::class.java)
    }

    //  退出登录
    fun logout() {
        sharePreferences().edit {
            clear()
        }
    }
}